package com.cskaoyan.service;

import com.cskaoyan.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

@Service
@Transactional(rollbackFor= Exception.class)
public class AccountServiceImpl implements AccountService{
    @Autowired
    AccountMapper accountMapper;
    @Autowired
    TransactionTemplate transactionTemplate;
    @Override
    public void transfer(int fromId, int destId, int money) {
        int fromMoney = accountMapper.selectMoneyById(fromId);
         int destMoney = accountMapper.selectMoneyById(destId);
        fromMoney -= money;  //如果转账成功，应该更新的money
        destMoney += money;  //如果转账成功，应该更新的money
        int finalFromMoney = fromMoney;
        int finalDestMoney = destMoney;
        //手动写事务
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                accountMapper.updateMoneyById(finalFromMoney, fromId);
                int i = 1 / 0;
                accountMapper.updateMoneyById(finalDestMoney, destId);
                return null;
            }
        });
//            accountMapper.updateMoneyById(fromMoney, fromId);
//            int i = 1 / 0;
//            accountMapper.updateMoneyById(destMoney, destId);
    }
}
